<template>
  <div class="container">
    <div class="header">
      <h1>编辑课程</h1>
    </div>

    <el-card class="form-card" v-loading="loading">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="course-form"
      >
        <el-form-item label="课程标题" prop="lessonName">
          <el-input v-model="form.lessonName" placeholder="请输入课程标题" />
        </el-form-item>

        <el-form-item label="课程图片" prop="leassonPictureUrl">
          <el-upload
            action="#"
            list-type="picture-card"
            :limit="1"
            :file-list="fileList"
            :auto-upload="false"
            :on-change="handleImageChange"
            accept="image/jpeg,image/png,image/gif"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div v-if="form.leassonPictureUrl" class="image-preview-container">
            <el-image 
              :src="form.leassonPictureUrl" 
              class="image-preview"
              :preview-src-list="[form.leassonPictureUrl]"
              preview-teleported
              fit="cover">
            </el-image>
          </div>
        </el-form-item>

        <el-form-item label="跳转链接" prop="jumpUrl">
          <el-input v-model="form.jumpUrl" placeholder="请输入跳转链接" />
        </el-form-item>

        <el-form-item label="讲师" prop="teacherId">
          <el-select v-model="form.teacherId" placeholder="请选择讲师">
            <el-option
              v-for="item in instructorOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="课程简介" prop="lessonDescription">
          <el-input
            v-model="form.lessonDescription"
            type="textarea"
            :rows="5"
            placeholder="请输入课程简介"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitting">保存</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { uploadFile } from '@/api/upload'
import { getTeacherSelectList } from '@/api/teacher'
import { updateLesson, getLessonById } from '@/api/lesson'

const router = useRouter()
const route = useRoute()
const formRef = ref(null)
const fileList = ref([])
const loading = ref(false)
const submitting = ref(false)
const courseId = route.params.id
const instructorOptions = ref([])
const imageFile = ref(null)

const form = reactive({
  lessonName: '',
  leassonPictureUrl: '',
  jumpUrl: '',
  teacherId: '',
  price: 0,
  duration: 1,
  students: 0,
  status: false,
  lessonDescription: '',
  deleteFlag: 0
})

const rules = reactive({
  lessonName: [
    { required: true, message: '请输入课程标题', trigger: 'blur' }
  ],
  teacherId: [
    { required: true, message: '请选择讲师', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入课程价格', trigger: 'blur' }
  ],
  duration: [
    { required: true, message: '请输入课时', trigger: 'blur' }
  ]
})

// 获取讲师列表
const fetchInstructors = async () => {
  try {
    const res = await getTeacherSelectList()
    if (res && res.code === 200 && res.data) {
      instructorOptions.value = res.data.map(item => ({
        value: item.id,
        label: item.teacherName
      }))
    } else {
      ElMessage.error('获取讲师列表失败')
    }
  } catch (error) {
    console.error('获取讲师列表失败', error)
    ElMessage.error('获取讲师列表失败：' + (error.message || '未知错误'))
  }
}

// 获取课程详情
const fetchCourseDetail = async () => {
  loading.value = true
  try {
    console.log('获取课程详情，ID：', courseId)

    if (!courseId) {
      ElMessage.error('缺少课程ID参数')
      router.push('/course')
      return
    }

    // 调用真实API获取课程详情
    const res = await getLessonById(courseId)
    console.log('课程详情返回数据：', res)

    if (res && res.code === 200) {
      if (!res.data) {
        ElMessage.warning('未找到课程数据')
        return
      }

      // 将后端返回的数据映射到表单
      const courseData = res.data

      // 确保ID被正确设置
      form.id = courseId

      // 映射其他字段
      form.lessonName = courseData.lessonName || ''
      form.leassonPictureUrl = courseData.leassonPictureUrl || ''
      form.jumpUrl = courseData.jumpUrl || ''
      form.teacherId = courseData.teacherId ? Number(courseData.teacherId) : ''
      form.lessonDescription = courseData.lessonDescription || ''
      form.deleteFlag = courseData.deleteFlag || 0

      // 其他可能的字段
      if (courseData.price !== undefined) form.price = courseData.price
      if (courseData.status !== undefined) {
        // 转换status为布尔类型（如果后端返回的是数字）
        form.status = courseData.status === 1 || courseData.status === true
      }
      if (courseData.duration !== undefined) form.duration = courseData.duration
      if (courseData.students !== undefined) form.students = courseData.students

      console.log('处理后的表单数据：', form)

      // 设置图片
      if (form.leassonPictureUrl) {
        fileList.value = [
          { name: 'course-image', url: form.leassonPictureUrl }
        ]
      }
    } else {
      ElMessage.error(res?.message || '获取课程详情失败')
    }
  } catch (error) {
    ElMessage.error('获取课程详情失败: ' + (error.message || '未知错误'))
    console.error('获取课程详情错误：', error)
  } finally {
    loading.value = false
  }
}

// 处理图片选择，先预览不上传
const handleImageChange = (file) => {
  imageFile.value = file.raw

  // 本地预览
  const reader = new FileReader()
  reader.onload = (e) => {
    // 显示本地预览图（上传成功前的临时显示）
    form.leassonPictureUrl = e.target.result
  }
  reader.readAsDataURL(imageFile.value)
}

// 提交表单
const submitForm = async () => {
  const valid = await formRef.value.validate().catch(() => false)

  if (!valid) return

  submitting.value = true
  try {
    // 如果有选择新图片，先上传图片
    if (imageFile.value) {
      const res = await uploadFile(imageFile.value, 'course')
      if (res && res.code === 200) {
        form.leassonPictureUrl = `http://localhost:8080/api`+res.message // 后端返回的图片URL
        ElMessage.success('图片上传成功')
      } else {
        throw new Error(res?.message || '图片上传失败')
      }
    }

    // 确保ID字段存在
    if (!form.id) {
      form.id = courseId
    }

    console.log('提交的表单数据：', form)

    // 实际调用API更新课程
    const res = await updateLesson(form)
    console.log('更新课程返回结果：', res)

    if (res && res.code === 200) {
      ElMessage.success('课程更新成功')
      router.push('/course')
    } else {
      throw new Error(res?.message || '更新失败')
    }
  } catch (error) {
    ElMessage.error('课程更新失败: ' + (error.message || '未知错误'))
    console.error('更新课程错误：', error)
  } finally {
    submitting.value = false
  }
}

const cancel = () => {
  router.push('/course')
}

onMounted(() => {
  fetchInstructors()
  fetchCourseDetail()
})
</script>

<style lang="scss" scoped>
.container {
  padding: 20px;

  .header {
    margin-bottom: 20px;

    h1 {
      font-size: 24px;
      margin: 0;
    }
  }

  .form-card {
    margin-bottom: 20px;
  }

  .course-form {
    max-width: 600px;
    margin-top: 20px;
  }

  .text-muted {
    color: #999;
    margin-left: 10px;
  }

  .image-preview-container {
    margin-top: 10px;
    text-align: center;
    
    .image-preview {
      width: 320px;
      height: 180px;
      object-fit: cover;
      border-radius: 4px;
    }
  }
}
</style>
